package com.cy.ppj.service.city.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cy.ppj.comm.constant.CacheConstants;
import com.cy.ppj.dao.mapper.city.CityMapper;
import com.cy.ppj.model.PageBean;
import com.cy.ppj.model.domian.city.City;
import com.cy.ppj.model.enums.CityStatus;
import com.cy.ppj.model.query.CityListAdminQuery;
import com.cy.ppj.model.vo.CityListAdminVO;
import com.cy.ppj.service.BaseService;
import com.cy.ppj.service.city.CityService;

/**
 * 城市service
 * @author: tanyilin
 * @create: 2018年8月13日 下午5:48:18
 */
@Service
public class CityServiceImpl extends BaseService implements CityService{

	@Autowired
	private CityMapper cityMapper;
	
	@Override
	@Cacheable(value = CacheConstants.CACHE_VALUE_2H)
	public List<City> getAllCityInCache() {
		City city = new City();
		city.setStatus(CityStatus.ENABLE);
		List<City> list = cityMapper.select(city);
		list.stream().forEach(c -> {
			c.setCreateTime(null);
			c.setUpdateTime(null);
			c.setStatus(null);
		});
		return list;
	}

	@Override
	public PageBean<CityListAdminVO> selectCityListAdmin(CityListAdminQuery query) {
		int total = cityMapper.selectCityListAdminCount(query);
		List<CityListAdminVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = cityMapper.selectCityListAdmin(query);
		}
		return new PageBean<>(list, total);
	}

	@Override
	@Transactional
	@CacheEvict(value = CacheConstants.CACHE_VALUE_2H, allEntries = true, beforeInvocation = true)
	public void addCity(City city) {
		City dbCity = new City();
		dbCity.setCity(city.getCity());
		dbCity = cityMapper.selectOne(dbCity);
		state(dbCity == null, "该城市已存在");
		//默认状态为-禁用
		city.setStatus(CityStatus.DISABLE);
		city.setCreateTime(new Date());
		cityMapper.insertSelective(city);
	}

	@Override
	@Transactional
	@CacheEvict(value = CacheConstants.CACHE_VALUE_2H, allEntries = true, beforeInvocation = true)
	public void updateStatus(Long cityId, CityStatus status) {

		City city = new City();
		city.setId(cityId);
		city.setStatus(status);
		city.setUpdateTime(new Date());
		cityMapper.updateByPrimaryKeySelective(city);
	}

}
